<?php

namespace app\admin\controller;
use app\common\controller\Backend;
use app\admin\model\Admin;
use think\Db;
use app\common\model\Materials;
use app\common\model\Attachment;
/**
 * 微信自动回复
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Autoreply extends Backend
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = [''];

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->model = model('app\common\model\Keywords');
    }
    // 收到消息回复
    public function message(){
        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            $data['wechat_id'] = $this->wechat_id;
            $data['update_at'] = time();
            $data['type'] = 'message';
            $wechatIds = $this->request->post('wechat/a');
            $result = db('replys')->insert($data,true,true);
            // 同步
            if(!empty($wechatIds) && is_array($wechatIds)){
                foreach ($wechatIds as $key => $wechatId) {
                    if(intval($wechatId) <= 0){
                        continue;
                    }
                    $data['wechat_id'] = $wechatId;
                    if($data['category'] == 'image'){
                        $data['media_id'] = (new Attachment)->getMedia_id($data['image'],$wechatId);
                    }
                    db('replys')->insert($data,true,true);
                }
            }
            $this->success('数据保持成功');
        }
        $row = db('replys')->where(['wechat_id'=>$this->wechat_id,'type'=>'message'])->find();
        $this->assign('row',$row);
        return $this->view->fetch('follow');
    }
    // 关注回复
    public function follow(){
        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            $wechatIds = $this->request->post('wechat/a');
            $data['wechat_id'] = $this->wechat_id;
            $data['update_at'] = time();
            $data['type'] = 'follow';
            $result = db('replys')->insert($data,true,true);
            // 同步
            if(!empty($wechatIds) && is_array($wechatIds)){
                foreach ($wechatIds as $key => $wechatId) {
                    if(intval($wechatId) <= 0){
                        continue;
                    }
                    $data['wechat_id'] = $wechatId;
                    if($data['category'] == 'image'){
                        $data['media_id'] = (new Attachment)->getMedia_id($data['image'],$wechatId);
                    }
                    db('replys')->insert($data,true,true);
                }
            }
            $this->success('数据保持成功');
        }
        $row = db('replys')->where(['wechat_id'=>$this->wechat_id,'type'=>'follow'])->find();
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    // 关键词回复
    public function keyword(){
        if ($this->request->isAjax()) {
            $map=[];
            $map['m.wechat_id'] = $this->wechat_id;
            list($where, $sort, $order, $offset, $limit) = $this->buildparams("a.name");
            $list = $this->model->alias("a")
                ->join("keywork_wechat m","m.keywork_id = a.id")
                ->field("a.*")
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }
    public function add(){

        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            if(empty($data['name'])){
                $this->error('规则名称不能为空');
            }
            $keywords = $this->request->post('mate/a');
            $mate = [];
            if(is_array($keywords)){
                foreach($keywords as $vo){
                    if(empty($vo['keyword'])){
                        continue;
                    }
                    $mate[] = ['keyword_id'=>'{keyword_id}','keyword'=>$vo['keyword'],'wechat_id'=>$this->wechat_id];
                }
            }
            if(empty($mate)){
                $this->error("请输入关键词");
            }
            // 文字回复
            if($data['type'] == 'text' && empty($data['content'])){
                $this->error('请输入回复内容');
            }
            // 图片回复
            if($data['type'] == 'image' && empty($data['image'])){
                $this->error('请上传回复图片');
            }
            // 图文
            if($data['type'] == 'material' && empty($data['material_id'])){
                $this->error('请选择图文信息');
            }
            $data['updated_at'] = time();
            $data['wechat_id'] = $this->wechat_id;
            Db::startTrans();
            try{
                $keyword_id = $this->model->insert($data,true,true);
                db('keywork_wechat')->insert(['keywork_id' => $keyword_id,'wechat_id'=>$this->wechat_id],true,true);
                $mates = json_encode($mate,JSON_UNESCAPED_UNICODE);
                $mates = preg_replace('/{keyword_id}/i', $keyword_id, $mates);
                $mates = json_decode($mates,true);
                db('keyword_mate')->insertAll($mates);
            }catch (\Exception $e){
                Db::rollback();
                $this->error('数据保存失败');
            }
            $wechatIds = $this->request->post('wechat/a');
            $wechatIds = $this->request->post('wechat/a');
            if(!empty($wechatIds) && is_array($wechatIds)){
                foreach($wechatIds as $wechatId){
                    if(intval($wechatId) <= 0){
                        continue;
                    }
                    \fast\Async::hook('keywork',['wechat_id'=>$this->wechat_id,'ids'=>$keyword_id,'wechatId'=>$wechatId]);
                }
            }
            Db::commit();
            $this->success('数据保存成功');

        }
        return $this->view->fetch();
    }
    public function edit($ids=null){
        $row = $this->model->where(['id'=>$ids])->find();
        if(empty($row)){
            $this->error('数据不存在');
        }
        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            if(empty($data['name'])){
                $this->error('规则名称不能为空');
            }
            $keywords = $this->request->post('mate/a');
            $mate = [];
            if(is_array($keywords)){
                foreach($keywords as $vo){
                    if(empty($vo['keyword'])){
                        continue;
                    }
                    $mate[] = ['keyword_id'=>$ids,'keyword'=>$vo['keyword'],'wechat_id'=>$this->wechat_id];
                }
            }
            if(empty($mate)){
                $this->error("请输入关键词");
            }
            // 文字回复
            if($data['type'] == 'text' && empty($data['content'])){
                $this->error('请输入回复内容');
            }
            // 图片回复
            if($data['type'] == 'image' && empty($data['image'])){
                $this->error('请上传回复图片');
            }
            // 图文
            if($data['type'] == 'mpnews' && empty($data['material_id'])){
                $this->error('请选择图文信息');
            }
            $data['updated_at'] = time();
            $data['wechat_id'] = $this->wechat_id;
            Db::startTrans();
            try{
                $this->model->where('id',$ids)->update($data);
                db('keyword_mate')->where('keyword_id',$ids)->where('wechat_id',$this->wechat_id)->delete();
                db('keyword_mate')->insertAll($mate);
            }catch (\Exception $e){
                Db::rollback();
                $this->error('数据保存失败');
            }
             Db::commit();
            $this->success('数据保存成功');

        }
        $t['text'] = $t['image'] = $t['mpnews'] = "none";
        if($row['type'] == 'text'){
            $t['text'] = "block";
        }
        if($row['type'] == 'image'){
            $t['image'] = "block";
        }
        if($row['type'] == 'mpnews'){
            $t['mpnews'] = "block";
            if((int)$row['material_id'] > 0){
                $material = Materials::get($row['material_id']);
                if(!empty($material)){
                    $material['items'] = (new Materials)->getMaterialItems($material->id);
                }
                $this->assign('material',$material);
            }
        }
        
        $keywords = $row['keyword'];
        if(empty($keywords)){
            $keywords[] = $row['name'];
        }
        $this->assign('keywords',$keywords);
        $this->assign('t',$t);
        $this->assign('row',$row);
        return $this->view->fetch();
    }
}